<?php

namespace app\index\dao;

use app\common\model\ConsultingMessage;
use ShidianUtil\Thinkphp\Dao\DaoTrait;
use think\Collection;

/**
 * ConsultingMessageDao 数据访问对象
 * Class ConsultingMessageDao
 * @package app\dao
 * @method ConsultingMessage findByPK(?int $id, $field = true)
 * @method \think\Collection selectAll(?int $page, ?int $page_size, $field = true)
 * @method ConsultingMessage insertActive(array $params, array $allow_field = [])
 * @method ConsultingMessage updateActive(ConsultingMessage $model, array $params, array $allow_field = [])
 * @method ConsultingMessage findAndUpdateActive(int $id, array $params, array $allow_field = [])
 * @method ConsultingMessage updateActiveByClosure(\Closure $closure, array $params, array $allow_field = [])
 * @method void deleteModel(ConsultingMessage $model)
 * @method void deleteById(int|array|\Closure $id, bool $force = false)
 * @link https://www.kancloud.cn/manual/thinkphp6_0/1037579
 * @link https://www.kancloud.cn/manual/think-orm/1257998
 * @link https://www.kancloud.cn/thinkphp/master-database-and-model/265551
 */
class ConsultingMessageDao
{
    use DaoTrait;

    /**
     * @var ConsultingMessage
     */
    private $baseModel;

    /**
     * ConsultingMessageDao constructor.
     */
    public function __construct()
    {
        $this->baseModel = ConsultingMessage::class;
    }

    /**
     * 查询咨询的历史消息
     * @param $consultingId
     * @param $memberId
     * @param int|null $page
     * @param int|null $page_size
     * @return Collection
     */
    public function selectConsultingHistory($consultingId, $memberId, $firstId, ?int $page, ?int $page_size): Collection
    {
        $query = ConsultingMessage::where('consultingId', $consultingId)
            ->where('isDel', 0)
            ->when(is_id($memberId), fn($query) => $query->whereIn('receiveId', ['0', $memberId]))
            ->with(['sender' => fn($query) => $query->sender()]);

        if (is_id($firstId)) {
            $query->where('id', '<', $firstId)->limit($page_size);
        } else {
            $query->paging($page, $page_size);
        }

        return $query->order('id', 'DESC')
            ->select();
    }

    /**
     * 读取单个消息
     * @param $id
     * @return ConsultingMessage|null
     */
    public function findConsultingMessage($id): ?ConsultingMessage
    {
        return ConsultingMessage::where('id', $id)
            ->with(['sender' => fn($query) => $query->sender()])
            ->find();
    }
}
